package cn.northsea.controller;


import cn.northsea.pojo.Material;
import cn.northsea.pojo.Role;
import cn.northsea.service.RoleService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/toAllocationRole")
    public String toAllocationRole(Integer pageNum, Integer userId, Model model) {
        List<Role> roleList = roleService.findAll2();
        List<Role> roles = roleService.findRoleByUid(userId);
        //将java集合转化为json数组JSON.toJSONString(roles)
        model.addAttribute("roles", JSON.toJSONString(roles));
        model.addAttribute("roleList", roleList);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("userId", userId);
        return "allocationRole";
    }

    @RequestMapping("/allocationRole")
    public String allocationRole(Integer pageNum, Integer userId, @RequestParam(name = "roleId") List<Integer> rids, Model model) {
        roleService.allocationRole(userId, rids);
        model.addAttribute("pageNum", pageNum);
        return "redirect:/user/findAll.do";
    }

    @RequestMapping("/findAll")
    public String findAll(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                          @RequestParam(required = false, defaultValue = "3") Integer pageSize,
                          @RequestParam(required = false, defaultValue = "") String likename,
                          Model model) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> roleList = null;
        PageInfo<Role> rolePageInfo = null;
        roleList = roleService.findAll(likename);
        rolePageInfo = new PageInfo<>(roleList);
        model.addAttribute("likename", likename);
        model.addAttribute("Page", rolePageInfo);
        return "roleList";
    }

    @RequestMapping("/addRole")
    public String addRole(Role role) {
        roleService.addRole(role);
        return "redirect:/role/findAll.do";
    }

    @RequestMapping("/checkRoleName")
    @ResponseBody
    public String checkRoleName(String roleName) {
        Role role = roleService.checkRoleName(roleName);
        if (role == null) {
            return "OK";
        } else {
            return "ERROR";
        }
    }


    @RequestMapping("/delRole2")
    public String delRole2(Integer[] ids) {
        roleService.delRole2(ids);
        return "redirect:/role/findAll.do";
    }


}
